<template>
  <view class="bg-white h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <view class="px-6 pt-12 pb-4 flex items-center justify-between border-b border-gray-100">
      <view class="flex items-center">
        <view class="text-blue-500 mr-3" @click="goBack">
          <text class="fas fa-chevron-left"></text>
        </view>
        <view class="text-xl font-bold">收藏集管理</view>
      </view>
      <view class="text-blue-500 font-medium" @click="showNewCollectionModal">
        <text class="fas fa-plus mr-1"></text>
        <text>新建</text>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="flex-1 px-6 py-4 overflow-auto">
      <!-- 收藏集列表 -->
      <view v-if="collectionList.length > 0" class="space-y-4">
        <view 
          v-for="(collection, index) in collectionList" 
          :key="collection.id"
          class="bg-white rounded-xl p-4 border border-gray-200 shadow-sm flex items-center justify-between group hover:border-blue-500 transition-colors collection-card"
        >
          <view class="flex items-center space-x-4">
            <view class="w-14 h-14 bg-gray-50 rounded-xl flex flex-col justify-center text-gray-700 text-xs border border-gray-100">
              <view class="font-medium text-left leading-tight mb-0.5 px-2">{{ collection.name }}</view>
              <view class="text-gray-500 text-left px-2">{{ collection.count }}个</view>
            </view>
            <view>
              <view class="font-medium text-gray-900">{{ collection.name }}</view>
              <view class="text-sm text-gray-500">{{ collection.count }}个图案</view>
            </view>
          </view>
          <view class="flex items-center space-x-2">
            <view 
              class="w-10 h-10 rounded-full bg-gray-100 text-gray-500 flex items-center justify-center hover:bg-blue-500 hover:text-white transition-colors" 
              @click="goToCollectionDetail(collection.id)"
            >
              <text class="fas fa-chevron-right"></text>
            </view>
            <view 
              class="w-10 h-10 rounded-full bg-gray-100 text-red-500 flex items-center justify-center hover:bg-red-500 hover:text-white transition-colors" 
              @click="showDeleteConfirm(collection)"
            >
              <text class="fas fa-trash-alt"></text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="flex flex-col items-center justify-center h-64">
        <view class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mb-4">
          <text class="fas fa-folder-open text-3xl text-gray-400"></text>
        </view>
        <view class="text-gray-500">还没有创建任何收藏集</view>
        <view 
          class="mt-4 bg-blue-500 text-white px-6 py-2 rounded-lg font-medium shadow-lg shadow-blue-200 hover:bg-blue-600 transition-colors" 
          @click="showNewCollectionModal"
        >
          创建第一个收藏集
        </view>
      </view>
    </view>

    <!-- 新建收藏集弹窗 -->
    <view 
      v-if="showCreateModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
      @click="hideNewCollectionModal"
    >
      <view 
        class="bg-white rounded-2xl p-6 w-5/6 max-w-md"
        @click.stop
      >
        <view class="text-xl font-bold mb-4">新建收藏集</view>
        <view class="mb-4">
          <view class="block text-sm font-medium text-gray-700 mb-1">收藏集名称</view>
          <input 
            v-model="newCollectionName"
            type="text" 
            class="w-full px-4 py-2 rounded-xl border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 outline-none transition-all" 
            placeholder="请输入收藏集名称"
          />
        </view>
        <view class="mb-6">
          <view class="block text-sm font-medium text-gray-700 mb-2">选择图标颜色</view>
          <view class="flex space-x-3">
            <view 
              v-for="(color, index) in colorOptions" 
              :key="color.value"
              :class="[
                'w-8 h-8 rounded-full flex items-center justify-center text-white cursor-pointer',
                color.bgClass,
                selectedColor === color.value ? 'border-2 border-white ring-2 ring-' + color.value + '-500' : ''
              ]"
              @click="selectColor(color.value)"
            >
              <text v-if="selectedColor === color.value" class="fas fa-check"></text>
            </view>
          </view>
        </view>
        <view class="flex space-x-3">
          <view 
            class="flex-1 px-4 py-2 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50 transition-colors text-center" 
            @click="hideNewCollectionModal"
          >
            取消
          </view>
          <view 
            class="flex-1 px-4 py-2 bg-blue-500 rounded-lg text-white font-medium hover:bg-blue-600 transition-colors text-center" 
            @click="createCollection"
          >
            创建
          </view>
        </view>
      </view>
    </view>

    <!-- 删除确认弹窗 -->
    <view 
      v-if="showDeleteModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
      @click="hideDeleteConfirm"
    >
      <view 
        class="bg-white rounded-2xl p-6 w-5/6 max-w-md"
        @click.stop
      >
        <view class="text-xl font-bold mb-2">删除收藏集</view>
        <view class="text-gray-600 mb-6">确定要删除"{{ selectedCollection?.name }}"收藏集吗？删除后将无法恢复。</view>
        <view class="flex space-x-3">
          <view 
            class="flex-1 px-4 py-2 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50 transition-colors text-center" 
            @click="hideDeleteConfirm"
          >
            取消
          </view>
          <view 
            class="flex-1 px-4 py-2 bg-red-500 rounded-lg text-white font-medium hover:bg-red-600 transition-colors text-center" 
            @click="confirmDelete"
          >
            删除
          </view>
        </view>
      </view>
    </view>

    <!-- Toast 提示 -->
    <view 
      v-if="showToast"
      class="fixed top-20 left-1/2 transform -translate-x-1/2 bg-gray-800 text-white px-4 py-2 rounded-lg z-50 toast"
      :class="{ active: showToast }"
    >
      {{ toastMessage }}
    </view>
  </view>
</template>

<script>
  import { collectionApi } from '@/api/index.js'
  
  export default {
  name: 'CollectionManagement',
  data() {
    return {
      showCreateModal: false,
      showDeleteModal: false,
      showToast: false,
      toastMessage: '',
      newCollectionName: '',
      selectedColor: 'blue',
      selectedCollection: null,
      colorOptions: [
        { value: 'blue', bgClass: 'bg-blue-500' },
        { value: 'green', bgClass: 'bg-green-500' },
        { value: 'purple', bgClass: 'bg-purple-500' },
        { value: 'red', bgClass: 'bg-red-500' },
        { value: 'yellow', bgClass: 'bg-yellow-500' },
        { value: 'gray', bgClass: 'bg-gray-500' }
      ],
      collectionList: [
        {
          id: 1,
          name: '风景收藏',
          count: 12,
          color: 'blue'
        },
        {
          id: 2,
          name: '动物收藏',
          count: 8,
          color: 'green'
        },
        {
          id: 3,
          name: '人物收藏',
          count: 5,
          color: 'purple'
        }
      ]
    }
  },
  
  onLoad() {
    this.loadCollections()
  },
  
  methods: {
    // 加载收藏集列表
    async loadCollections() {
      try {
        const result = await collectionApi.getUserCollections()
        
        if (result.errCode === 0 && result.data) {
          this.collectionList = result.data.map(collection => ({
            id: collection._id,
            name: collection.name,
            count: collection.pattern_count || 0,
            color: collection.color || 'blue',
            createdAt: collection.created_at,
            updatedAt: collection.updated_at
          }))
        } else {
          // 如果API失败，保持原有的模拟数据
          console.warn('加载收藏集失败，使用模拟数据')
        }
      } catch (error) {
        console.error('加载收藏集失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 跳转到收藏集详情页
    goToCollectionDetail(collectionId) {
      uni.navigateTo({
        url: `/pages/collection/detail?id=${collectionId}`
      })
    },
    
    // 显示新建收藏集弹窗
    showNewCollectionModal() {
      this.showCreateModal = true
      this.newCollectionName = ''
      this.selectedColor = 'blue'
    },
    
    // 隐藏新建收藏集弹窗
    hideNewCollectionModal() {
      this.showCreateModal = false
    },
    
    // 选择颜色
    selectColor(color) {
      this.selectedColor = color
    },
    
    // 创建收藏集
    async createCollection() {
      if (!this.newCollectionName.trim()) {
        this.showToastMessage('请输入收藏集名称')
        return
      }
      
      try {
        const result = await collectionApi.createCollection({
          name: this.newCollectionName.trim(),
          color: this.selectedColor,
          description: ''
        })
        
        if (result.errCode === 0) {
          const newCollection = {
            id: result.data._id,
            name: result.data.name,
            count: 0,
            color: result.data.color || this.selectedColor,
            createdAt: result.data.created_at
          }
          
          this.collectionList.unshift(newCollection)
          this.hideNewCollectionModal()
          this.showToastMessage('收藏集创建成功')
        } else {
          throw new Error(result.message || '创建失败')
        }
      } catch (error) {
        console.error('创建收藏集失败:', error)
        this.showToastMessage(error.message || '创建失败')
      }
    },
    
    // 显示删除确认弹窗
    showDeleteConfirm(collection) {
      this.selectedCollection = collection
      this.showDeleteModal = true
    },
    
    // 隐藏删除确认弹窗
    hideDeleteConfirm() {
      this.showDeleteModal = false
      this.selectedCollection = null
    },
    
    // 确认删除收藏集
    confirmDelete() {
      if (this.selectedCollection) {
        const index = this.collectionList.findIndex(c => c.id === this.selectedCollection.id)
        if (index > -1) {
          this.collectionList.splice(index, 1)
          this.showToastMessage('收藏集已删除')
          this.saveCollections()
        }
      }
      this.hideDeleteConfirm()
    },
    
    // 显示Toast提示
    showToastMessage(message) {
      this.toastMessage = message
      this.showToast = true
      
      // 3秒后自动隐藏
      setTimeout(() => {
        this.showToast = false
      }, 3000)
    },
    
    // 加载收藏集列表
    loadCollections() {
      try {
        const collections = uni.getStorageSync('collections')
        if (collections && collections.length > 0) {
          this.collectionList = collections
        }
      } catch (e) {
        console.error('加载收藏集失败:', e)
      }
    },
    
    // 保存收藏集列表
    saveCollections() {
      try {
        uni.setStorageSync('collections', this.collectionList)
      } catch (e) {
        console.error('保存收藏集失败:', e)
      }
    }
  }
}
</script>

<style scoped>
/* TailwindCSS 工具类样式 */
.bg-white { background-color: #ffffff; }
.bg-gray-50 { background-color: #f9fafb; }
.bg-gray-100 { background-color: #f3f4f6; }
.bg-gray-200 { background-color: #e5e7eb; }
.bg-gray-400 { background-color: #9ca3af; }
.bg-gray-500 { background-color: #6b7280; }
.bg-gray-700 { background-color: #374151; }
.bg-gray-800 { background-color: #1f2937; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-blue-600 { background-color: #2563eb; }
.bg-green-500 { background-color: #22c55e; }
.bg-purple-500 { background-color: #8b5cf6; }
.bg-red-500 { background-color: #ef4444; }
.bg-red-600 { background-color: #dc2626; }
.bg-yellow-500 { background-color: #eab308; }
.bg-black { background-color: #000000; }

.text-white { color: #ffffff; }
.text-gray-400 { color: #9ca3af; }
.text-gray-500 { color: #6b7280; }
.text-gray-600 { color: #4b5563; }
.text-gray-700 { color: #374151; }
.text-gray-900 { color: #111827; }
.text-blue-500 { color: #3b82f6; }
.text-red-500 { color: #ef4444; }

.border-b { border-bottom-width: 1px; }
.border-gray-100 { border-color: #f3f4f6; }
.border-gray-200 { border-color: #e5e7eb; }
.border-gray-300 { border-color: #d1d5db; }
.border-white { border-color: #ffffff; }
.border-2 { border-width: 2px; }

.h-screen { height: 100vh; }
.h-24 { height: 96px; }
.h-64 { height: 256px; }
.w-8 { width: 32px; }
.h-8 { height: 32px; }
.w-10 { width: 40px; }
.h-10 { height: 40px; }
.w-14 { width: 56px; }
.h-14 { height: 56px; }
.w-24 { width: 96px; }
.w-5\/6 { width: 83.333333%; }
.w-full { width: 100%; }

.flex { display: flex; }
.flex-col { flex-direction: column; }
.flex-1 { flex: 1; }

.px-2 { padding-left: 8px; padding-right: 8px; }
.px-4 { padding-left: 16px; padding-right: 16px; }
.px-6 { padding-left: 24px; padding-right: 24px; }
.py-2 { padding-top: 8px; padding-bottom: 8px; }
.py-4 { padding-top: 16px; padding-bottom: 16px; }
.pt-12 { padding-top: 48px; }
.pb-4 { padding-bottom: 16px; }
.p-4 { padding: 16px; }
.p-6 { padding: 24px; }
.mr-1 { margin-right: 4px; }
.mr-3 { margin-right: 12px; }
.mb-1 { margin-bottom: 4px; }
.mb-2 { margin-bottom: 8px; }
.mb-4 { margin-bottom: 16px; }
.mb-6 { margin-bottom: 24px; }
.mb-0\.5 { margin-bottom: 2px; }
.mt-4 { margin-top: 16px; }

.max-w-md { max-width: 448px; }

.rounded-lg { border-radius: 8px; }
.rounded-xl { border-radius: 12px; }
.rounded-2xl { border-radius: 16px; }
.rounded-full { border-radius: 9999px; }

.items-center { align-items: center; }
.justify-center { justify-content: center; }
.justify-between { justify-content: space-between; }

.text-center { text-align: center; }
.text-left { text-align: left; }
.text-xs { font-size: 12px; }
.text-sm { font-size: 14px; }
.text-xl { font-size: 20px; }
.text-3xl { font-size: 30px; }

.font-bold { font-weight: 700; }
.font-medium { font-weight: 500; }

.space-x-2 > * + * { margin-left: 8px; }
.space-x-3 > * + * { margin-left: 12px; }
.space-x-4 > * + * { margin-left: 16px; }
.space-y-4 > * + * { margin-top: 16px; }

.shadow-sm { box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); }
.shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); }
.shadow-blue-200 { box-shadow: 0 10px 15px -3px rgba(147, 197, 253, 0.4), 0 4px 6px -2px rgba(147, 197, 253, 0.2); }

.transition-colors { transition: color 0.2s ease, background-color 0.2s ease; }
.transition-all { transition: all 0.2s ease; }

.overflow-auto { overflow: auto; }

.fixed { position: fixed; }
.inset-0 { top: 0; right: 0; bottom: 0; left: 0; }

.z-50 { z-index: 50; }

.leading-tight { line-height: 1.25; }

.bg-opacity-50 { background-color: rgba(0, 0, 0, 0.5); }

.outline-none { outline: none; }

.focus\:border-blue-500:focus { border-color: #3b82f6; }
.focus\:ring-2:focus { box-shadow: 0 0 0 2px #93c5fd; }
.focus\:ring-blue-200:focus { box-shadow: 0 0 0 2px rgba(147, 197, 253, 0.5); }

.transform { transform: translateX(-50%); }
.-translate-x-1\/2 { transform: translateX(-50%); }

.top-20 { top: 80px; }
.left-1\/2 { left: 50%; }

.cursor-pointer { cursor: pointer; }

/* 自定义样式 */
.hover\:bg-gray-50:hover { background-color: #f9fafb; }
.hover\:bg-blue-500:hover { background-color: #3b82f6; }
.hover\:bg-blue-600:hover { background-color: #2563eb; }
.hover\:bg-red-500:hover { background-color: #ef4444; }
.hover\:bg-red-600:hover { background-color: #dc2626; }
.hover\:text-white:hover { color: #ffffff; }
.hover\:border-blue-500:hover { border-color: #3b82f6; }

/* 收藏集卡片样式 */
.collection-card {
  transition: all 0.3s ease;
}

.collection-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 模态框样式 */
input {
  border: 1px solid #d1d5db;
  border-radius: 12px;
  padding: 8px 16px;
  font-size: 14px;
  transition: all 0.2s ease;
}

input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
  outline: none;
}

/* Toast提示样式 */
.toast {
  opacity: 0;
  transition: all 0.3s ease;
  transform: translate(-50%, -20px);
}

.toast.active {
  opacity: 1;
  transform: translate(-50%, 0);
}

/* Font Awesome 图标 */
.fas {
  font-family: "Font Awesome 6 Free";
  font-weight: 900;
}

.fa-chevron-left:before { content: "\f053"; }
.fa-plus:before { content: "\f067"; }
.fa-chevron-right:before { content: "\f054"; }
.fa-trash-alt:before { content: "\f2ed"; }
.fa-folder-open:before { content: "\f07c"; }
.fa-check:before { content: "\f00c"; }

/* 颜色环样式 */
.ring-2 { box-shadow: 0 0 0 2px; }
.ring-blue-500 { box-shadow: 0 0 0 2px #3b82f6; }
.ring-green-500 { box-shadow: 0 0 0 2px #22c55e; }
.ring-purple-500 { box-shadow: 0 0 0 2px #8b5cf6; }
.ring-red-500 { box-shadow: 0 0 0 2px #ef4444; }
.ring-yellow-500 { box-shadow: 0 0 0 2px #eab308; }
.ring-gray-500 { box-shadow: 0 0 0 2px #6b7280; }
</style>
